<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <h2>👤 个人中心</h2>
      </template>

      <el-descriptions :column="1" border>
        <el-descriptions-item label="用户名">
          {{ user?.username }}
        </el-descriptions-item>
        <el-descriptions-item label="昵称">
          {{ user?.nickname || '未设置' }}
        </el-descriptions-item>
        <el-descriptions-item label="邮箱">
          {{ user?.email || '未设置' }}
        </el-descriptions-item>
        <el-descriptions-item label="手机号">
          {{ user?.phone || '未设置' }}
        </el-descriptions-item>
        <el-descriptions-item label="钱包地址">
          <div v-if="user?.walletAddress" style="display: flex; align-items: center; gap: 10px;">
            <el-tag type="success">{{ user.walletAddress }}</el-tag>
            <el-tag type="warning" size="small">已绑定，不可修改</el-tag>
            <el-button @click="showUnbindDialog" type="danger" size="small">
              解绑
            </el-button>
          </div>
          <div v-else>
            <el-tag type="warning">未绑定</el-tag>
            <el-text type="danger" size="small">（必须绑定才能使用NFT功能）</el-text>
            <el-button @click="showBindDialog" type="primary" size="small" style="margin-left: 10px;">
              立即绑定
            </el-button>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="注册时间">
          {{ formatDate(user?.createdAt) }}
        </el-descriptions-item>
      </el-descriptions>

      <div class="actions">
        <el-button @click="showEditDialog" type="primary">
          编辑资料
        </el-button>
      </div>
    </el-card>

    <!-- 绑定钱包对话框 -->
    <el-dialog 
      v-model="bindDialogVisible" 
      title="绑定钱包" 
      width="500px"
    >
      <div class="bind-wallet-content">
        <el-alert
          title="什么是钱包绑定？"
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        >
          绑定钱包后，你可以：
          <ul>
            <li>使用该钱包铸造和交易 NFT</li>
            <li>将区块链资产与账户关联</li>
            <li>享受更好的平台体验</li>
          </ul>
        </el-alert>

        <div v-if="connectedAccount" class="wallet-info">
          <p><strong>检测到钱包：</strong></p>
          <el-tag type="success" size="large">{{ formatAddress(connectedAccount) }}</el-tag>
        </div>
        <div v-else>
          <el-empty description="请先连接 MetaMask 钱包">
            <el-button type="primary" @click="connectWallet" :loading="connecting">
              连接 MetaMask
            </el-button>
          </el-empty>
        </div>
      </div>

      <template #footer>
        <el-button @click="bindDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleBind" 
          :disabled="!connectedAccount"
          :loading="binding"
        >
          确认绑定
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑资料对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="编辑资料" 
      width="500px"
    >
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="昵称">
          <el-input v-model="editForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdate" :loading="updating">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import userStore from '../store/userStore';
import web3Service from '../services/web3Service';

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Profile',
  setup() {
    const user = computed(() => userStore.getters.getUser());
    const bindDialogVisible = ref(false);
    const editDialogVisible = ref(false);
    const connectedAccount = ref(null);
    const connecting = ref(false);
    const binding = ref(false);
    const updating = ref(false);

    const editForm = ref({
      nickname: '',
      email: '',
      phone: '',
    });

    const formatAddress = (address) => {
      if (!address) return '';
      return `${address.substring(0, 10)}...${address.substring(address.length - 8)}`;
    };

    const formatDate = (dateString) => {
      if (!dateString) return '未知';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN');
    };

    const showBindDialog = () => {
      connectedAccount.value = web3Service.getAccount();
      bindDialogVisible.value = true;
    };

    const showUnbindDialog = async () => {
      try {
        await ElMessageBox.confirm(
          '解绑后将无法使用该钱包进行 NFT 操作，确定要解绑吗？',
          '确认解绑',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        );

        await userStore.actions.linkWallet(null);
        ElMessage.success('钱包解绑成功！');
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error(error.message || '解绑失败');
        }
      }
    };

    const connectWallet = async () => {
      try {
        connecting.value = true;
        const account = await web3Service.connectWallet();
        connectedAccount.value = account;
        ElMessage.success('钱包连接成功！');
      } catch (error) {
        ElMessage.error(error.message || '连接失败');
      } finally {
        connecting.value = false;
      }
    };

    const handleBind = async () => {
      try {
        binding.value = true;

        // 检查该钱包是否已被其他用户绑定
        // (这个检查应该在后端进行，这里简化处理)
        
        await userStore.actions.linkWallet(connectedAccount.value);
        
        ElMessage.success('钱包绑定成功！');
        bindDialogVisible.value = false;
      } catch (error) {
        ElMessage.error(error.message || '绑定失败');
      } finally {
        binding.value = false;
      }
    };

    const showEditDialog = () => {
      editForm.value = {
        nickname: user.value?.nickname || '',
        email: user.value?.email || '',
        phone: user.value?.phone || '',
      };
      editDialogVisible.value = true;
    };

    const handleUpdate = async () => {
      try {
        updating.value = true;

        const updateData = {
          nickname: editForm.value.nickname?.trim() || null,
          email: editForm.value.email?.trim() || null,
          phone: editForm.value.phone?.trim() || null,
        };

        await userStore.actions.updateUser(user.value.id, updateData);
        
        ElMessage.success('资料更新成功！');
        editDialogVisible.value = false;
      } catch (error) {
        ElMessage.error(error.message || '更新失败');
      } finally {
        updating.value = false;
      }
    };

    onMounted(() => {
      connectedAccount.value = web3Service.getAccount();
    });

    return {
      user,
      bindDialogVisible,
      editDialogVisible,
      connectedAccount,
      connecting,
      binding,
      updating,
      editForm,
      formatAddress,
      formatDate,
      showBindDialog,
      showUnbindDialog,
      connectWallet,
      handleBind,
      showEditDialog,
      handleUpdate,
    };
  },
};
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 2rem auto;
  padding: 0 1rem;
}

.profile-card h2 {
  margin: 0;
  color: #303133;
}

.actions {
  margin-top: 2rem;
  text-align: center;
}

.bind-wallet-content {
  padding: 1rem 0;
}

.wallet-info {
  text-align: center;
  padding: 2rem;
}

.wallet-info p {
  margin-bottom: 1rem;
  color: #606266;
}
</style>

